/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.caigourenyuan;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.activity.MultipleChoiceActivity;
import com.mingmen.canting.adapter.SearchAdapter;
import com.mingmen.canting.adapter.SearchSupplierAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ClearEditText;
import com.mingmen.canting.gongyingshang.SupplierShopActivity;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.label.adapter.MultipleRecyclerAdapter;
import com.mingmen.canting.label.bean.LabelTestBean;
import com.mingmen.canting.label.recycler.OnItemClickListener;
import com.mingmen.canting.model.GongYingShangModel;

import com.mingmen.canting.model.SearchModel;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.zhenban.ZhenBanReplaceFragmentActivity;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class SelectGongYingActivity extends Activity {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    @BindView(R.id.btn_add_address)
    Button btnRegister;


    @BindView(R.id.rv_gongyingshang)
    SwipeRecyclerView rv_gongyingshang;
    private GongYingShangAdapter mAdapter;
    private List<GongYingShangModel.DataBean> mDataList = new ArrayList<>();
    String detailIds;
    String token;

    @BindView(R.id.btn_submit)
    Button btn_submit;
    int flag = 0;
    String gongName;
    String position;

    String str_receive;

    String applyId_s;
    String commpanyNames;

    private RecyclerView mRecyclerView;
    private List<LabelTestBean> mListData = new ArrayList<>();
    private MultipleRecyclerAdapter mAdapter_label;

    @BindView(R.id.checkbox_all)
    CheckBox checkbox_all;
    private int resurtResurant = 200;
    @BindView(R.id.main_search)
    ClearEditText main_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gongying);
        ButterKnife.bind(this);
        textCenter.setText("选择供应商");
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();

        token = (String) SharePreferenceUtil.get(this, "token", "");
        positionSet.clear();
        checkTYpeId.clear();
        checkTYpeNameSet.clear();
        idSend.clear();
        nameList.clear();
        mListData.clear();
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mListData = new ArrayList<>();
        mAdapter_label = new MultipleRecyclerAdapter(SelectGongYingActivity.this, mListData);
        mRecyclerView.setAdapter(mAdapter_label);
        detailIds = getIntent().getStringExtra("detailIds");
        Log.d("DetailsID", detailIds);
        position = getIntent().getStringExtra("position");

        applyId_s = getIntent().getStringExtra("applyId_s");
        commpanyNames = getIntent().getStringExtra("commpanyNames");
        Log.d("SelectGongYing", commpanyNames.toString());

        String d[] = applyId_s.split(",");
        List<String> stringList = new ArrayList<String>();


        List<String> commpanyList = new ArrayList<String>();
        String e[] = commpanyNames.split(",");
        for (int i = 0; i < d.length; i++) {
            stringList.add(d[i]);
        }
        for (int i = 0; i < e.length; i++) {
            commpanyList.add(e[i]);
        }
        Log.d("APPIDASsdf", applyId_s);
        Log.d("commpanyNamescommpanyNames", commpanyNames);
        for (int i = 0; i < commpanyList.size(); i++) {
//            Log.d("stringListstringList", stringList.get(i));
            mListData.add(new LabelTestBean(stringList.get(i), commpanyList.get(i)));
        }


    /*    for (int i = 0; i < stringList.size(); i++) {
            mListData.add(new LabelTestBean(stringList.get(i), commpanyList.get(i)));
        }
        for (int i = 0; i < mListData.size(); i++) {
            Log.d("SELECTGONGYING", mListData.get(i).getTagId());
        }*/
        mAdapter_label.update(mListData);
        mAdapter_label.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                addOrRemove(position);
            }

            @Override
            public void OnItemLongClick(View view, int position) {

            }
        });
        checkbox_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (int i = 0; i < mListData.size(); i++) {
                        addOrRemove(i);
                    }
                } else {
                    for (int i = 0; i < mListData.size(); i++) {
                        addOrRemove(i);
                    }
                }

            }
        });

        mRecyclerView.setLayoutManager(gridLayoutManager);

        rv_gongyingshang.setLayoutManager(new LinearLayoutManager(this));


        mAdapter = new GongYingShangAdapter(this);

        rv_gongyingshang.setAdapter(mAdapter);
        DividerItemDecoration divider = new DividerItemDecoration(SelectGongYingActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(SelectGongYingActivity.this, R.drawable.custom_gray));

//        rv_gongyingshang.addItemDecoration(divider);
        mAdapter.setOnItemClickListener(new GongYingShangAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<GongYingShangModel.DataBean> groupList) {

                switch (view.getId()) {
                    case R.id.btn_select:
                        HttpResponse.changeSupplier(token, detailIds, applyId_s, mDataList.get(pos).getSupplierId(), new StringCallback(SelectGongYingActivity.this) {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                BaseBean baseBean = new BaseBean();
                                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                Toast.makeText(SelectGongYingActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                                positionSet.clear();
                                checkTYpeId.clear();
                                checkTYpeNameSet.clear();
                                idSend.clear();
                                nameList.clear();
                                mListData.clear();
//                                Intent intent = new Intent(SelectGongYingActivity.this, CaiGouRenDaiListragment.class);
                                Intent intent = new Intent(SelectGongYingActivity.this, DaiCaiGouListfragment.class);
                                intent.putExtra("flag", flag + "");
                                intent.putExtra("gongName", mDataList.get(pos).getSupplierName() + "");
                                intent.putExtra("position", position);
                                setResult(100, intent);
                                finish();
                            }
                        });
                        break;
                    case R.id.ivAvatar:
//                        startActivity(new Intent(SelectGongYingActivity.this,GongYingShangDetawilActivity.class ));
                        Intent intent = new Intent(SelectGongYingActivity.this, GongYingShangDetawilActivity.class);
                        intent.putExtra("supplierId", mDataList.get(pos).getSupplierId());
                        startActivity(intent);

                        break;
                    case R.id.layout_top:
                        if (mAdapter.isParentItem(pos)) {
                            // 换取parent position
                            final int parentPosition = mAdapter.parentItemPosition(pos);
                            // 判断parent是否打开了二级菜单
                            if (mAdapter.isExpanded(parentPosition)) {
                                mDataList.get(parentPosition).setExpend(false);
                                mAdapter.notifyParentChanged(parentPosition);
                                // 关闭该parent下的二级菜单
                                mAdapter.collapseParent(parentPosition);
                            } else {
                                mDataList.get(parentPosition).setExpend(true);
                                mAdapter.notifyParentChanged(parentPosition);
                                // 打开该parent下的二级菜单
                                mAdapter.expandParent(parentPosition);
                            }
                        } else {
                            // 换取parent position
                            int parentPosition = mAdapter.parentItemPosition(pos);
                            // 换取child position
                            int childPosition = mAdapter.childItemPosition(pos);
                            String message = String.format("我是%1$d爸爸的%2$d儿子", parentPosition, childPosition);
//                    Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();

                        }
                        break;
                    case R.id.btn_connect:
                        intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + groupList.get(pos).getSupplierTel());
                        intent.setData(data);
                        startActivity(intent);
                        break;

                }

            }

        });

        getData(token, detailIds, applyId_s, "", "");
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

//                getSearch();
                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            String keyWord = main_search.getText().toString().trim();
                            getData(token, detailIds, applyId_s, main_search.getText().toString(), "");

                            return true;
                        default:
                            return true;
                    }
                }

                return false;
            }
        });
        main_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    getData(token, detailIds, applyId_s, "", "");

                } else if (s.toString().length() < 1) {


                } else {

                }


//                startActivityForResult(intent, resurtResurant);
            }
        });
    }

    public void getData(String token, String detailIds, String applyId_s, String keyword, String limitDate) {
        HttpResponse.getSupplierByCommodity(token, detailIds, applyId_s, keyword, "", new StringCallback(SelectGongYingActivity.this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                Log.d("SeleCTGONGYING", s);
                if (mDataList.size() > 0) {
                    mDataList.clear();
                }
                GongYingShangModel gongYingShangModel = new GongYingShangModel();
                gongYingShangModel = GsonUtil.GsonToBean(s, GongYingShangModel.class);
                mDataList.addAll(gongYingShangModel.getData());
                mAdapter.setGroupList(mDataList);
                mAdapter.notifyDataSetChanged();
            }
        });
    }


    @OnClick({R.id.text_return, R.id.linear_return, R.id.btn_add_address, R.id.btn_submit, R.id.text_center})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_return:


            case R.id.linear_return:

                positionSet.clear();
                checkTYpeId.clear();
                checkTYpeNameSet.clear();
                idSend.clear();
                nameList.clear();
                mListData.clear();
                finish();
                break;
            case R.id.btn_add_address:
                Log.d("btn_adddressaddress", idSend.toString());
                String mysend = MyStringUtils.returnStringBuffer(idSend);
                Log.d("mysendmysend", mysend);
                getData(token, detailIds, mysend, "", "");

                break;
            case R.id.btn_submit:

                if (checkTYpeId.size() == 0) {
                    Toast.makeText(this, "请选择线下自采的商品", Toast.LENGTH_SHORT).show();
                } else {
                    intent = new Intent(SelectGongYingActivity.this, XianXiaZiCaiActivity.class);
//                intent.putExtra("applyId_s", applyId_s);
//                intent.putExtra("commpanyNames", commpanyNames);
                    intent.putExtra("applyId_s", checkTYpeId.toString());

                    intent.putExtra("commpanyNames", nameList.toString());
                    startActivityForResult(intent, resurtResurant);
                }


                break;
            case R.id.text_center:
                startActivity(new Intent(SelectGongYingActivity.this, MultipleChoiceActivity.class));
                break;
        }
    }

    public static Set<Integer> positionSet = new HashSet<>();
    public Set<String> checkTYpeId = new HashSet<>();


    public Set<String> checkTYpeNameSet = new HashSet<>();
    List<String> idSend = new ArrayList<>();
    List<String> nameList = new ArrayList<>();
    private boolean selectMode = true; //选择模式 多选或者单选  true  多选

    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            // 如果包含，则撤销选择
            positionSet.remove(position);
//            checkTYpeNameSet.remove(mListData.get(position).getTagName());
            checkTYpeNameSet.remove(mListData.get(position).getTagName());
            checkTYpeId.remove(mListData.get(position).getTagId());
        } else {
            // 如果不包含，则添加
            positionSet.add(position);
//            checkTYpeNameSet.add(mListData.get(position).getTagName());
            checkTYpeNameSet.add(mListData.get(position).getTagName());
            checkTYpeId.add(mListData.get(position).getTagId());
        }

        if (positionSet.size() == 0) {
            // 如果没有选中任何的item，则退出多选模式
            mAdapter_label.notifyDataSetChanged();
            selectMode = false;
        } else {
            // 更新列表界面，否则无法显示已选的item
            mAdapter_label.notifyDataSetChanged();
        }
        Log.e("info", positionSet.toString());
        if (idSend.size() > 0) {
            idSend.clear();
        }
//        idSend=Arrays.asList(checkTYpeNameSet.toString());
//        List<String> result = new ArrayList<>(checkTYpeNameSet);

        idSend = new ArrayList<>(checkTYpeId);
        nameList = new ArrayList<>(checkTYpeNameSet);

        Log.e("ArraysArraysArrays", idSend.toString());
        Log.e("nameList", nameList.toString());
//        idSend.add(result.toString());

    }

    String idSend_receiver;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == resurtResurant) {


            positionSet.clear();
            checkTYpeId.clear();
            checkTYpeNameSet.clear();
            idSend.clear();
            nameList.clear();
            HttpResponse.changeSupplier(token, detailIds, applyId_s, "1", new StringCallback(SelectGongYingActivity.this) {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    BaseBean baseBean = new BaseBean();
                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                    Toast.makeText(SelectGongYingActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();

                }
            });
            idSend_receiver = data.getStringExtra("idSend");
            Log.d("idSend_receiver", idSend_receiver);
            Intent intent = new Intent(SelectGongYingActivity.this, CaiGouRenDaiListragment.class);
            intent.putExtra("flag", "1");
            intent.putExtra("gongName", "选择供应商");
            intent.putExtra("position", position);
            intent.putExtra("idSend_receiver", idSend_receiver);
            setResult(100, intent);
            finish();

        }

    }
}